package venus

import (
	"net/http"
	"sync"
	"time"

	"github.com/sethgrid/multibar"
	log "github.com/sirupsen/logrus"
)

var (
	lock = sync.Mutex{}
)

type Status struct {
	Url      string
	Status   int
	Time     time.Time
	UsedTime time.Duration
	Req      string
	Method   string
	Res      string
	BarFunc  multibar.ProgressFunc
}

type LogPanel struct {
	Cache map[string]Status
	Bar   *multibar.BarContainer
}

func NewLogPanel() (panel *LogPanel) {
	b, err := multibar.New()
	if err != nil {
	}
	return &LogPanel{
		Bar:   b,
		Cache: make(map[string]Status),
	}
}

func (p *LogPanel) UpdateReq(url string, req *http.Request) {
	// o, ok := p.Cache[url]
	lock.Lock()
	defer lock.Unlock()
	p.Cache[url] = Status{
		Url:     url,
		Time:    time.Now(),
		Method:  req.Method,
		Req:     ReqString(req),
		BarFunc: p.Bar.MakeBar(1, url),
	}
}

func (p *LogPanel) UpdateRes(url string, res *http.Response) {
	o, ok := p.Cache[url]
	lock.Lock()
	defer lock.Unlock()
	if ok {
		o.Res = ResString(res)
		o.Status = res.StatusCode
		o.UsedTime = time.Now().Sub(o.Time)
		o.BarFunc(1)
		// for i, v := range p.Bar.Bars{
		// 	if v == p.
		// }
		// p.Bar.Println(url, color.New(color.Bold,color.FgGreen).Sprint(" [finished] "))
	} else {
		log.Error("url not exists:", url)
	}
}

func (p *LogPanel) Listen() {
	p.Bar.Listen()
}
